package com.senlingspace.common.utils;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * 生成随机编号
 *
 * @author lebronjames
 */
public class NumberGenerator {

    private static final int DEFAULT_LENGTH = 12; // 默认长度
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final String NUMBER = "0123456789";
    private static final Random RANDOM = new Random();
    private static final Set<String> generatedNumbers = new HashSet<>();

    private NumberGenerator() {
    }

    public static String getCharacters() {
        return getCharacters(DEFAULT_LENGTH);
    }

    public static String productNumber() {
        return productNumber(8);
    }

    public static synchronized String getCharacters(int length) {
        StringBuilder projectNumber;
        do {
            projectNumber = new StringBuilder(length);
            for (int i = 0; i < length; i++) {
                projectNumber.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
            }
        } while (generatedNumbers.contains(projectNumber.toString()));

        generatedNumbers.add(projectNumber.toString());
        return projectNumber.toString();
    }

    public static synchronized String productNumber(int length) {
        StringBuilder ProductNumber;
        do {
            ProductNumber = new StringBuilder(length);
            for (int i = 0; i < length; i++) {
                ProductNumber.append(NUMBER.charAt(RANDOM.nextInt(NUMBER.length())));
            }
        } while (generatedNumbers.contains(ProductNumber.toString()));

        generatedNumbers.add(ProductNumber.toString());
        return ProductNumber.toString();
    }

    // public static void main(String[] args) {
    //     // 测试生成的项目编号
    //     for (int i = 0; i < 8; i++) {
    //         System.out.println(productNumber());
    //     }
    // }
}
